﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Lyx.Entities
{
    class Entity
    {
        public Vector2 vPosition = new Vector2(0.0f, 0.0f);
        Vector2 vOldPosition = new Vector2(0.0f, 0.0f);

        public float fRotation = 0.0f;
        float fOldRotation = 0.0f;

        public int iWidth = 0;
        public int iHeight = 0;

        float fAngleStart = 0.0f;
        float fDistanceToCenter = 0.0f;

        public bool bCollide = false;

        public Tools.BoundingRect boundingRect;
        public Tools.SpriteKey spriteKey;

        public Entity(Vector2 _vPosition, Vector2 _vCenter, Tools.SpriteKey _spriteKey)
        {
            vPosition = _vPosition;

            iWidth = _spriteKey.iWidth;
            iHeight = _spriteKey.iHeight;

            fDistanceToCenter = (float)Math.Sqrt(Math.Pow(vPosition.X, 2) + Math.Pow(vPosition.Y, 2));

            spriteKey = new Tools.SpriteKey(_spriteKey);
            boundingRect = new Tools.BoundingRect(new Rectangle(0, 0, iWidth, iHeight), 0.0f);

            fAngleStart = ((float)Math.Asin(vPosition.X / fDistanceToCenter) + 1.57079633f);

            if (_vPosition.Y < 0)
                fAngleStart *= -1.0f;

            //if (_vPosition.X != _vCenter.X && _vPosition.Y != _vCenter.Y)
            // UpdatePosition(vPosition+_vCenter, 0.0f);
        }

        public void UpdatePosition(Vector2 _vCenterOfRoot, float _fRotation)
        {
            SaveOldPosition(_vCenterOfRoot, _fRotation);

            this.fRotation = _fRotation;
            this.vPosition.X = ((fDistanceToCenter) * (float)Math.Cos(this.fRotation + fAngleStart)) + _vCenterOfRoot.X;
            this.vPosition.Y = ((fDistanceToCenter) * (float)Math.Sin(this.fRotation + fAngleStart)) + _vCenterOfRoot.Y;

            boundingRect.UpdatePosition(vPosition, fRotation);
        }

        public void SaveOldPosition(Vector2 _vCenterOfRoot, float _fRotation)
        {
            vOldPosition = vPosition;
            fOldRotation = fRotation;
        }

        public void CancelPosition()
        {
            vPosition = vOldPosition;
            fRotation = fOldRotation;

            boundingRect.UpdatePosition(vOldPosition, fOldRotation);
        }

        public bool Intersects(Entity _entity)
        {
            return this.boundingRect.Intersects(_entity.boundingRect);
        }
    }
}
